1343C - Alternating Subsequence - CodeForces Solution


dp greedy two pointers *1200

Please click on ads to support us..

Python Code:

t=int(input())
while t>0:
    sum=0
    t-=1
    n=int(input())
    l=list(map(int,input().split()))
    temp=[0]*n
    for i in range(n):
        if i==0 or l[i]*l[i-1]<0:             temp[i]=l[i]
            if i!=0 and l[i]*l[i-1]:sum+=temp[i-1]
        else:
            temp[i]=l[i]=max(l[i],l[i-1])
    sum+=temp[-1]
    print(sum)

C++ Code:

#include <bits/stdc++.h>
using namespace std;

#define int long long
#define pb push_back

int32_t main(){
    int T = 1;
    cin>>T;
    while(T--){
        int n;
        cin>>n;
        int a[n];
        vector <int> v;
        for(int i=0;i<n;i++){
            cin>>a[i];
        }
        if(n==1){
            cout<<a[0]<<endl;
            continue;
        }
        int i=0, j=1;
        int mx = a[i];
        int ans = 0;
        while(i<n){
            while(j<n && a[i]*a[j]>0){
                mx = max(mx, a[j]);
                j++;
            }
            ans += mx;
            i = j;
            j++;
            mx = a[i];
        }
        cout<<ans<<endl;
    }
    return 0;
}


Comments

Submit
0 Comments
More Questions

938A - Word Correction
159C - String Manipulation 10
258A - Little Elephant and Bits
1536C - Diluc and Kaeya
1428C - ABBB
1557A - Ezzat and Two Subsequences
255A - Greg's Workout
1059A - Cashier
1389C - Good String
1561A - Simply Strange Sort
1337B - Kana and Dragon Quest game
137C - History
1443C - The Delivery Dilemma
6C - Alice Bob and Chocolate
1077C - Good Array
285B - Find Marble
6A - Triangle
1729A - Two Elevators
1729B - Decode String
1729C - Jumping on Tiles
1729E - Guess the Cycle Size
553B - Kyoya and Permutation
1729D - Friends and the Restaurant
1606C - Banknotes
580C - Kefa and Park
342A - Xenia and Divisors
1033A - King Escape
39D - Cubical Planet
1453A - Cancel the Trains
645A - Amity Assessment